package com.h3bpm.kumhosunny.okr.controller;

import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Entity.DataModel.BizObject;
import OThinker.H3.Entity.Instance.Data.InstanceData;
import OThinker.H3.Entity.Notification.Notification;
import OThinker.H3.Portal.webservices.BPMService;
import OThinker.H3.Portal.webservices.Entity.BPMServiceResult;
import OThinker.H3.Portal.webservices.Entity.DataItemParam;
import OThinker.H3.Portal.webservices.impl.BPMServiceImpl;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.kumhosunny.common.utils.SqlUtil;
import data.DataTable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

/**
 * @author zhibiao
 */
@Controller
@RequestMapping(value = "/Portal/DepartmentOkrController")
public class DepartmentOkrDraft extends ControllerBase {

    public static final Logger LOGGER = (Logger) LoggerFactory.getLogger(DepartmentOkrDraft.class);

    private BPMService bpmService = new BPMServiceImpl();

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String getFunctionCode() {
        return null;
    }

    //http://localhost:8081/Portal/DepartmentOkrController/StartProcessOKRreviews?instanceId=f28d8e89-c141-4dee-93cf-701f269b24d4

    /***
     * OKR发起流程节点
     * @param instanceId
     * @return
     */
    @RequestMapping(value = "/StartProcessOKRreviews")
    @ResponseBody
    public String StartProcessOKRreviews(String instanceId) {

        String result = "200";

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> datas = instanceData.getBizObject().getValueTable();

            //数据映射
            String teamType = (String) datas.get("TeamClassify");
            String teamName = (String) datas.get("TeamName");
            String nowYear = (String) datas.get("Year11");
            String quarter = (String) datas.get("Quarter");

            //OKR子表数据
            BizObject[] okrSonTable = null;
            String suffixStr = "";

            //获取子表数据
            if (null != datas.get("ObjectiveKeyResultsV2")) {
                okrSonTable = (BizObject[]) datas.get("ObjectiveKeyResultsV2");
                suffixStr = "V2";
            } else if (null != datas.get("ObjectiveKeyResultsV1")) {
                okrSonTable = (BizObject[]) datas.get("ObjectiveKeyResultsV1");
                suffixStr = "V1";
            } else {
                okrSonTable = (BizObject[]) datas.get("OkrContent");
            }

            List<HashMap<String, Object>> okrValues = new ArrayList<>();
            for (BizObject bizObject : okrSonTable) {
                HashMap<String, Object> maps = new HashMap<>();

                if ("V2".equals(suffixStr)) {
                    maps.put("Objective1", bizObject.getValueTable().get("KeyTaskSupportStrategic"));
                    maps.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                    maps.put("responsibility", bizObject.getValueTable().get("responsibility"));
                    maps.put("finishDate", bizObject.getValueTable().get("finishDate"));
                    okrValues.add(maps);
                } else {
                    maps.put("Objective1", bizObject.getValueTable().get("Objective" + suffixStr));
                    maps.put("KeyResults", bizObject.getValueTable().get("KeyResults" + suffixStr));
                    maps.put("responsibility", bizObject.getValueTable().get("responsibility" + suffixStr));
                    maps.put("finishDate", bizObject.getValueTable().get("finishDate" + suffixStr));
                    okrValues.add(maps);
                }

            }

            //okr评估人子表
            /*BizObject[] okrReviewForm= (BizObject[]) datas.get("TheJudgesReview");

            //封装数据
            List<HashMap<String,Object>> reviewPersonValues=new ArrayList<>();

            for(BizObject bizObject:okrReviewForm){
                HashMap<String,Object> maps=new HashMap<>();
                maps.put("Assessors",bizObject.getValueTable().get("theJudeges"));
                reviewPersonValues.add(maps);
            }*/

            //发起流程的数据
            List<DataItemParam> params = new ArrayList<>();
            params.add(new DataItemParam("teamClassify", teamType));
            params.add(new DataItemParam("teamName", teamName));
            params.add(new DataItemParam("year1", nowYear));
            params.add(new DataItemParam("quarter", quarter));
            params.add(new DataItemParam("OKRreview", okrValues));

            //发起人
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());

            //发起流程
            BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "OKRreviews", user.getCode(), false, params);

            //等待1秒
            Thread.sleep(500);
            String workItemId = SqlUtil.doQuery(String.format("select  objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), user.getObjectID())).getRows().get(0).getString(0);

            String pc_url = "http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID=" + workItemId + "&time=" + System.currentTimeMillis();
            String mobile_url = "http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/" + workItemId + "?time=" + System.currentTimeMillis();

            //发送消息通知用户
            //子流程数据
            InstanceData sonData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);

            Notification notification = new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk, null, user.getObjectID(),
                    user.getDingTalkAccount(), null, 0, bpmServiceResult.getInstanceId(),
                    "团队OKR完成情况及绩效评价" + sonData.getInstanceContext().getInstanceName(), "您有一条流程待办,点击查看", null, mobile_url, pc_url, null);

            getEngine().getNotifier().Notify(notification);


        } catch (Exception e) {
            result = "500";
            e.printStackTrace();
        }

        return result;

    }

    /***
     * 发起子流程评委评估
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/DepartmentOkrController/StartProcessPersonAssessment?instanceId=b9f1f072-c5b6-4b44-ba27-37023ea96976
    @RequestMapping(value = "/StartProcessPersonAssessment")
    @ResponseBody
    public String StartProcessReviewPersonAssessment(String instanceId) {

        String resultCode = "200";

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();

            //数据映射
            String teamType = (String) valueTables.get("teamClassify");
            String teamName = (String) valueTables.get("teamName");
            String nowYear = (String) valueTables.get("year1");
            String quarter = (String) valueTables.get("quarter");

            //数据封装
            Map<String, List> resultMaps = new HashMap<>();

            //okr数据
            BizObject[] okrBizObject = (BizObject[]) valueTables.get("OKRreview");
            List<HashMap<String, Object>> okrValues = new ArrayList<>();
            for (BizObject bizObject : okrBizObject) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("Objective1", bizObject.getValueTable().get("Objective1"));
                maps.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                maps.put("performance", bizObject.getValueTable().get("Performance1"));
                maps.put("responsibility", bizObject.getValueTable().get("responsibility"));
                maps.put("finishDate", bizObject.getValueTable().get("finishDate"));
                okrValues.add(maps);
            }

            //纬度
            BizObject[] teamBizObject = (BizObject[]) valueTables.get("teamLeader");
            List<HashMap<String, Object>> tempValues = new ArrayList<>();
            if(null!=teamBizObject){
                for (BizObject bizObject : teamBizObject) {
                    HashMap<String, Object> maps = new HashMap<>();
                    maps.put("aspects1", bizObject.getValueTable().get("item"));
                    maps.put("descriptions", bizObject.getValueTable().get("description"));
                    tempValues.add(maps);
                }
            }


            //okr下季度计划数据
            BizObject[] nextOkrBizObject = (BizObject[]) valueTables.get("OKRnextQuarter");
            List<HashMap<String, Object>> okrNextValues = new ArrayList<>();
            if(null!=nextOkrBizObject){
                for (BizObject bizObject : nextOkrBizObject) {
                    HashMap<String, Object> maps = new HashMap<>();
                    maps.put("Objective", bizObject.getValueTable().get("ObjectiveNext"));
                    maps.put("KeyResultsNext", bizObject.getValueTable().get("KeyResults"));
                    maps.put("ResponsibilityNext", bizObject.getValueTable().get("responsibility"));
                    maps.put("TargetdateNext", bizObject.getValueTable().get("finishDate"));
                    okrNextValues.add(maps);
                }
            }

            //评审人
            BizObject[] evaluteChartTables = (BizObject[]) valueTables.get("CommentTotal");

            String[] assessorsPerson=null;
            //所有评审人
            if(null!=evaluteChartTables){
                assessorsPerson = new String[evaluteChartTables.length];

                if (null != evaluteChartTables && evaluteChartTables.length != 0) {

                    for (int i = 0; i < evaluteChartTables.length; i++) {
                        assessorsPerson[i] = (String) evaluteChartTables[i].getValueTable().get("Assessors");
                    }

                }
            }

            if (null != evaluteChartTables && evaluteChartTables.length != 0) {

                for (BizObject bizObject : evaluteChartTables) {
                    List<DataItemParam> params = new ArrayList<>();
                    params.add(new DataItemParam("teamClassify", teamType));
                    params.add(new DataItemParam("TeamName", teamName));
                    params.add(new DataItemParam("Year1", nowYear));
                    params.add(new DataItemParam("Quarter", quarter));
                    params.add(new DataItemParam("reporter", instanceData.getInstanceContext().getOriginator()));
                    params.add(new DataItemParam("evaluater", bizObject.getValueTable().get("Assessors")));
                    //okr绩效数据
                    params.add(new DataItemParam("OKRperformance", okrValues));
                    //okr下季度计划数据
                    params.add(new DataItemParam("OkrNextSeason1", okrNextValues));
                    //纬度
                    params.add(new DataItemParam("teamLeader12", tempValues));
                    //父流程ID
                    params.add(new DataItemParam("parentInstanceId", instanceId));
                    resultMaps.put(bizObject.getValueTable().get("Assessors").toString(), params);
                }

            }

            //开始发起子流程
            /*for (String userCode : resultMaps.keySet()) {
                User nowUser = (User) getEngine().getOrganization().GetUnit(userCode);
                LOGGER.info("> MeritsSon: 发起子流程 >发起人:" + nowUser.getCode());
                BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "TeamOKRevaluates", nowUser.getCode(), false, resultMaps.get(userCode));

                //等待1秒
                Thread.sleep(500);
                String workItemId = SqlUtil.doQuery(String.format("select  objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), nowUser.getObjectID())).getRows().get(0).getString(0);

                String pc_url = "http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID=" + workItemId + "&time=" + System.currentTimeMillis();
                String mobile_url = "http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/" + workItemId + "?time=" + System.currentTimeMillis();

                //发送消息通知用户
                //子流程数据
                InstanceData sonData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);

                Notification notification = new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk, null, nowUser.getObjectID(),
                        nowUser.getDingTalkAccount(), null, 0, bpmServiceResult.getInstanceId(),
                        "团队绩效评价-" + teamType + "-" + quarter + sonData.getInstanceContext().getInstanceName(), "您有一条流程待办,点击查看", null, mobile_url, pc_url, null);

                getEngine().getNotifier().Notify(notification);

                LOGGER.info("> " + objectMapper.writeValueAsString(bpmServiceResult));
            }*/


            //okr数据
            BizObject[] okrAtBizObject = (BizObject[]) valueTables.get("OKRreview");
            List<HashMap<String, Object>> okrAtValues = new ArrayList<>();
            for (BizObject bizObject : okrAtBizObject) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("Objective1", bizObject.getValueTable().get("Objective1"));
                maps.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                maps.put("Performance1", bizObject.getValueTable().get("Performance1"));
                maps.put("responsibility", bizObject.getValueTable().get("responsibility"));
                maps.put("finishDate", bizObject.getValueTable().get("finishDate"));
                okrAtValues.add(maps);
            }

            //纬度
            BizObject[] teamAtBizObject = (BizObject[]) valueTables.get("teamLeader");
            List<HashMap<String, Object>> tempAtValues = new ArrayList<>();
            for (BizObject bizObject : teamAtBizObject) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("item", bizObject.getValueTable().get("item"));
                maps.put("description", bizObject.getValueTable().get("description"));
                tempAtValues.add(maps);
            }

            //okr下季度计划数据
            BizObject[] nextOkrAtBizObject = (BizObject[]) valueTables.get("OKRnextQuarter");
            List<HashMap<String, Object>> okrNextAtValues = new ArrayList<>();
            for (BizObject bizObject : nextOkrAtBizObject) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("ObjectiveNext", bizObject.getValueTable().get("ObjectiveNext"));
                maps.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                maps.put("responsibility", bizObject.getValueTable().get("responsibility"));
                maps.put("finishDate", bizObject.getValueTable().get("finishDate"));
                okrNextAtValues.add(maps);
            }

            //根据团队下是否有负责人决定是否发起流程
            String[] headPerson = null;
            String querySql = "SELECT userId FROM i_okr_headuser WHERE groupType='" + teamType + "' AND userId!='"+instanceData.getInstanceContext().getOriginator()+"'";
            DataTable dataTable = SqlUtil.doQuery(querySql);
            boolean startHeadProcessFlag = false;

            if (dataTable.getRows().size() > 0) {
                if (null != dataTable.getRows().get(0).getString(0) && !"".equals(dataTable.getRows().get(0).getString(0))) {
                    startHeadProcessFlag = true;
                    headPerson = new String[dataTable.getRows().size()];
                    for (int i = 0; i < dataTable.getRows().size(); i++) {
                        headPerson[i] = dataTable.getRows().get(i).getString(0);
                    }
                }
            }

            //commentAtTotal
            List<HashMap<String, Object>> commentFormValues = new ArrayList<>();
            for(int i=0;i<headPerson.length;i++){
                HashMap<String, Object> map=new HashMap<>();
                map.put("Assessors",headPerson[i]);
                map.put("performanceRate","");
                map.put("coefficient","");
                map.put("OKR","");
                map.put("PersonalResults","");
                map.put("coreValue","");
                map.put("personalLearning","");
                map.put("nextProcessComment","");
                commentFormValues.add(map);
            }

            //是否可以正常发起
            String formCreateState=valueTables.get("StartAtProcessState").toString();

            if (startHeadProcessFlag && "success".equals(formCreateState)) {
                //同时发起At Start
                List<DataItemParam> atParams = new ArrayList<>();
                atParams.add(new DataItemParam("teamClassify", teamType));
                atParams.add(new DataItemParam("TeamName", teamName));
                atParams.add(new DataItemParam("Year1", nowYear));
                atParams.add(new DataItemParam("Quarter", quarter));
                atParams.add(new DataItemParam("ATteamParticipant", headPerson));
                atParams.add(new DataItemParam("OKRreview1", okrAtValues));
                atParams.add(new DataItemParam("teamLeader1", tempAtValues));
                atParams.add(new DataItemParam("OKRnextQuarter1", okrNextAtValues));
                atParams.add(new DataItemParam("commentAtTotal", commentFormValues));

                User nowUser = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());
                LOGGER.info("> MeritsSon: 发起子流程 >发起人:" + nowUser.getCode());
                BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "PersonalOKRreviews", nowUser.getCode(), true, atParams);

                //等待1秒
                Thread.sleep(500);
                String workItemId = SqlUtil.doQuery(String.format("select  objectid from ot_workitemfinished where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), nowUser.getObjectID())).getRows().get(0).getString(0);

                String pc_url = "http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID=" + workItemId + "&time=" + System.currentTimeMillis();
                String mobile_url = "http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/" + workItemId + "?time=" + System.currentTimeMillis();

                //发送消息通知用户
                //子流程数据
                InstanceData sonData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);

                Notification notification = new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk, null, nowUser.getObjectID(),
                        nowUser.getDingTalkAccount(), null, 0, bpmServiceResult.getInstanceId(),
                        "团队负责人绩效评价-" + teamType + "-" + quarter + sonData.getInstanceContext().getInstanceName(), "您有一条流程待办,点击查看", null, mobile_url, pc_url, null);

                getEngine().getNotifier().Notify(notification);

                LOGGER.info("> " + objectMapper.writeValueAsString(bpmServiceResult));

                //At End
            }

        } catch (Exception e) {
            e.printStackTrace();
            resultCode = "500";
        }

        return resultCode;

    }

    /***
     * 发起 at 子流程
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/DepartmentOkrController/StartProcessReviewAtPerson?instanceId=9371c0b8-70b4-43c8-9ed5-9c1955ca67db
    @RequestMapping(value = "/StartProcessReviewAtPerson")
    @ResponseBody
    public String StartProcessReviewAtPerson(String instanceId) {
        String resultCode = "200";

        InstanceData instanceData = null;
        try {
            instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();

            //数据映射
            String teamType = (String) valueTables.get("teamClassify");
            String teamName = (String) valueTables.get("teamName");
            String nowYear = (String) valueTables.get("year1");
            String quarter = (String) valueTables.get("quarter");

            //数据封装
            Map<String, List> resultMaps = new HashMap<>();

            //okr数据
            BizObject[] okrBizObject = (BizObject[]) valueTables.get("OKRreview1");
            List<HashMap<String, Object>> okrValues = new ArrayList<>();
            for (BizObject bizObject : okrBizObject) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("Objective1", bizObject.getValueTable().get("Objective1"));
                maps.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                maps.put("performance", bizObject.getValueTable().get("Performance1"));
                maps.put("responsibility", bizObject.getValueTable().get("responsibility"));
                maps.put("finishDate", bizObject.getValueTable().get("finishDate"));
                okrValues.add(maps);
            }

            //纬度
            BizObject[] teamBizObject = (BizObject[]) valueTables.get("teamLeader1");
            List<HashMap<String, Object>> tempValues = new ArrayList<>();
            for (BizObject bizObject : teamBizObject) {
                HashMap<String, Object> maps = new HashMap<>();
                maps.put("items11", bizObject.getValueTable().get("item"));
                maps.put("description11", bizObject.getValueTable().get("description"));
                tempValues.add(maps);
            }

            //okr下季度计划数据
            BizObject[] nextOkrBizObject = (BizObject[]) valueTables.get("OKRnextQuarter1");
            List<HashMap<String, Object>> okrNextValues = new ArrayList<>();

            if (nextOkrBizObject.length != 0) {
                for (BizObject bizObject : nextOkrBizObject) {
                    HashMap<String, Object> maps = new HashMap<>();
                    maps.put("ObjectiveNext", bizObject.getValueTable().get("ObjectiveNext"));
                    maps.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                    maps.put("responsibility", bizObject.getValueTable().get("responsibility"));
                    maps.put("finishDate", bizObject.getValueTable().get("finishDate"));
                    okrNextValues.add(maps);
                }
            }

            //评审人
            BizObject[] evaluteChartTables = (BizObject[]) valueTables.get("commentAtTotal");

            if (null != evaluteChartTables && evaluteChartTables.length != 0) {

                for (BizObject bizObject : evaluteChartTables) {
                    List<DataItemParam> params = new ArrayList<>();
                    params.add(new DataItemParam("teamClassify", teamType));
                    params.add(new DataItemParam("TeamName", teamName));
                    params.add(new DataItemParam("Year1", nowYear));
                    params.add(new DataItemParam("Quarter", quarter));
                    params.add(new DataItemParam("reporter", instanceData.getInstanceContext().getOriginator()));
                    params.add(new DataItemParam("evaluater", bizObject.getValueTable().get("Assessors")));
                    //okr绩效数据
                    params.add(new DataItemParam("OKRperformance3", okrValues));
                    //okr下季度计划数据
                    params.add(new DataItemParam("OKRnextSeason", okrNextValues));
                    //纬度
                    params.add(new DataItemParam("teamLeader123", tempValues));
                    //父流程ID
                    params.add(new DataItemParam("parentInstanceId", instanceId));
                    resultMaps.put(bizObject.getValueTable().get("Assessors").toString(), params);
                }

            }


            //开始发起子流程
            for (String userCode : resultMaps.keySet()) {
                User nowUser = (User) getEngine().getOrganization().GetUnit(userCode);
                LOGGER.info("> MeritsSon: 发起子流程 >发起人:" + nowUser.getCode());
                BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "TeamLeaderOKRevaluates", nowUser.getCode(), false, resultMaps.get(userCode));

                //等待1秒
                Thread.sleep(500);
                String workItemId = SqlUtil.doQuery(String.format("select  objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), nowUser.getObjectID())).getRows().get(0).getString(0);

                String pc_url = "http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID=" + workItemId + "&time=" + System.currentTimeMillis();
                String mobile_url = "http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/" + workItemId + "?time=" + System.currentTimeMillis();

                //发送消息通知用户
                //子流程数据
                InstanceData sonData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);

                Notification notification = new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk, null, nowUser.getObjectID(),
                        nowUser.getDingTalkAccount(), null, 0, bpmServiceResult.getInstanceId(),
                        "团队负责人绩效评价-" + teamType + "-" + quarter + sonData.getInstanceContext().getInstanceName(), "您有一条流程待办,点击查看", null, mobile_url, pc_url, null);

                getEngine().getNotifier().Notify(notification);

                LOGGER.info("> " + objectMapper.writeValueAsString(bpmServiceResult));
            }


        } catch (Exception e) {
            resultCode = e.getMessage();
            e.printStackTrace();
        }


        return resultCode;
    }

    /***
     * OKR  at 评估数据返回
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/DepartmentOkrController/StartAtProcessReviewBackData?instanceId=b0eab424-aa50-4923-97ed-2d139afd8c14
    @RequestMapping(value = "/StartAtProcessReviewBackData")
    @ResponseBody
    public String StartAtProcessReviewBackData(String instanceId) {
        String resultCode = "200";

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();
            //评估人
            String reviewPerson = valueTables.get("evaluater").toString();

            //父流程ID
            String parentInstanceId = valueTables.get("parentInstanceId").toString();

            //绩效等级
            String rateLevel = valueTables.get("performanceRate").toString();
            //绩效系数
            String rateNumber = valueTables.get("coefficient").toString();
            String okrStr = valueTables.get("OKR").toString();
            String kpiResult = valueTables.get("KPIresults").toString();
            String teamBuilder = valueTables.get("teamBuilding").toString();
            String learningStr = valueTables.get("learningAndImprovement").toString();

            //当前时间
            Date date = new Date();

            //父流程数据
            InstanceData parentInstanceDate = new InstanceData(getEngine(), parentInstanceId, User.AdministratorID);
            BizObject[] parentFormData = (BizObject[]) parentInstanceDate.getBizObject().getValueTable().get("commentAtTotal");

            for (BizObject bizObject : parentFormData) {
                HashMap<String, Object> objectHashMap = bizObject.getValueTable();

                //确定当前账户
                if (objectHashMap.get("Assessors").equals(reviewPerson)) {
                    //父表赋值
                    bizObject.setItem("performanceRate", rateLevel);
                    bizObject.setItem("coefficient", rateNumber);
                    bizObject.setItem("OKR", okrStr);
                    bizObject.setItem("PersonalResults", kpiResult);
                    bizObject.setItem("coreValue", teamBuilder);
                    bizObject.setItem("personalLearning", learningStr);
                    bizObject.setItem("commentDate", date);
                    LOGGER.info("> MeritsSon: 子流程数据返回父表,子流程ID:" + instanceId);
                    break;
                }

            }
            //数据先录入后计算

            //遍历判断当前汇总状态
            Integer successPerson = 0;
            for (BizObject bizObject : parentFormData) {
                HashMap<String, Object> objectHashMap = bizObject.getValueTable();
                //计算已完成人
                if (null != objectHashMap.get("performanceRate") && !"".equals(objectHashMap.get("performanceRate"))) {
                    successPerson++;  //已完成汇总人数+1
                }
            }

            //遍历完成判断 && 提交过来已完成人数+1
            if (successPerson != parentFormData.length) {
                Integer noperson = (parentFormData.length - successPerson);
                parentInstanceDate.getBizObject().setItem("evaluateChartState", "未完成人数:" + noperson);
            } else {
                parentInstanceDate.getBizObject().setItem("evaluateChartState", "已完成");
            }

            //保存父表所有数据
            parentInstanceDate.Submit();


        } catch (Exception e) {
            resultCode = "500";
            e.printStackTrace();
        }


        return resultCode;
    }

    /***
     * OKR评估数据返回
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/DepartmentOkrController/StartProcessReviewBackData?instanceId=5966993a-8b72-4e5f-b7b5-1d932f63fe4d
    @RequestMapping(value = "/StartProcessReviewBackData")
    @ResponseBody
    public String StartProcessReviewBackData(String instanceId) {

        String resultCode = "200";

        try {
            InstanceData instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();
            //评估人
            String reviewPerson = valueTables.get("evaluater").toString();

            //父流程ID
            String parentInstanceId = valueTables.get("parentInstanceId").toString();

            //绩效等级
            String rateLevel = valueTables.get("performanceRate").toString();
            //绩效系数
            String rateNumber = valueTables.get("coefficient").toString();
            String okrStr = valueTables.get("OKR").toString();
            String kpiResult = valueTables.get("KPIresults").toString();
            String teamBuilder = valueTables.get("teamBuilding").toString();

            //下季度OKR制定评价
            String nextProcessComment = valueTables.get("OkrNextQuarterEvaluate").toString();
            //当前时间
            Date date = new Date();

            //父流程数据
            InstanceData parentInstanceDate = new InstanceData(getEngine(), parentInstanceId, User.AdministratorID);
            BizObject[] parentFormData = (BizObject[]) parentInstanceDate.getBizObject().getValueTable().get("CommentTotal");

            for (BizObject bizObject : parentFormData) {
                HashMap<String, Object> objectHashMap = bizObject.getValueTable();

                //确定当前账户
                if (objectHashMap.get("Assessors").equals(reviewPerson)) {
                    //父表赋值
                    bizObject.setItem("performanceRate", rateLevel);  //绩效等级
                    bizObject.setItem("coefficient", rateNumber);  //绩效系数
                    bizObject.setItem("OKR", okrStr); //OKR
                    bizObject.setItem("Results", kpiResult);   //业绩达成
                    bizObject.setItem("teamBuildings", teamBuilder);  //团队建设
                    bizObject.setItem("nextProcessComment", nextProcessComment);
                    bizObject.setItem("commentDate", date);
                    LOGGER.info("> MeritsSon: 子流程数据返回父表,子流程ID:" + instanceId);
                    break;
                }

            }
            //数据先录入后计算

            //遍历判断当前汇总状态
            Integer successPerson = 0;
            for (BizObject bizObject : parentFormData) {
                HashMap<String, Object> objectHashMap = bizObject.getValueTable();
                //计算已完成人
                if (null != objectHashMap.get("performanceRate") && !"".equals(objectHashMap.get("performanceRate"))) {
                    successPerson++;  //已完成汇总人数+1
                }
            }

            //遍历完成判断 && 提交过来已完成人数+1
            if (successPerson != parentFormData.length) {
                Integer noperson = (parentFormData.length - successPerson);
                parentInstanceDate.getBizObject().setItem("evaluateChartState", "未完成人数:" + noperson);
            } else {
                parentInstanceDate.getBizObject().setItem("evaluateChartState", "已完成");
            }

            //保存父表所有数据
            parentInstanceDate.Submit();


        } catch (Exception e) {
            resultCode = "500";
            e.printStackTrace();
        }


        return resultCode;

    }

    /***
     * 发起下季度okr制定
     * @param instanceId
     * @return
     */
    //http://localhost:8081/Portal/DepartmentOkrController/StartNextOkrProcess?instanceId=201f1d66-9813-44b7-b4c6-c70494fa4c8e
    @RequestMapping(value = "/StartNextOkrProcess")
    @ResponseBody
    public String StartNextOkrProcess(String instanceId) {
        String resultCode = "200";
        InstanceData instanceData = null;
        try {
            instanceData = new InstanceData(getEngine(), instanceId, User.AdministratorID);
            HashMap<String, Object> valueTables = instanceData.getBizObject().getValueTable();
            //数据映射
            String teamType = (String) valueTables.get("teamClassify");
            String teamName = (String) valueTables.get("teamName");
            String nowYear = (String) valueTables.get("year1");
            //季度
            String quarter = (String) valueTables.get("quarter");
            //当前季度
            Integer nowQuarterInt = Integer.parseInt(String.valueOf(quarter.toCharArray()[1]));
            if (nowQuarterInt == 4) {
                //最后一个季度 年+1
                nowYear = String.valueOf((Integer.parseInt(nowYear) + 1));
                nowQuarterInt = 0;
            }
            String nextQuarter = "Q" + (nowQuarterInt + 1);

            //封装okr评价以及制定的下季度okr
            List<HashMap<String, Object>> parentOkrValues = new ArrayList<>();
            BizObject[] parentOkrBizObject = (BizObject[]) valueTables.get("OKRnextQuarter");
            for (BizObject bizObject : parentOkrBizObject) {
                HashMap<String, Object> values = new HashMap<>();
                values.put("Objective", bizObject.getValueTable().get("ObjectiveNext"));
                values.put("KeyResults", bizObject.getValueTable().get("KeyResults"));
                values.put("responsibility", bizObject.getValueTable().get("responsibility"));
                values.put("finishDate", bizObject.getValueTable().get("finishDate"));
                parentOkrValues.add(values);
            }

            List<HashMap<String, Object>> commentValues = new ArrayList<>();
            BizObject[] commentBizObject = (BizObject[]) valueTables.get("CommentTotal");
            for (BizObject bizObject : commentBizObject) {
                HashMap<String, Object> values = new HashMap<>();
                values.put("theJudeges", bizObject.getValueTable().get("Assessors"));
                values.put("Comments", bizObject.getValueTable().get("nextProcessComment"));
                /*   values.put("CommentDate",bizObject.getValueTable().get("commentDate"));*/
                commentValues.add(values);
            }
            //最终评审人的下季度okr制定
            HashMap<String, Object> lastCommentValue = new HashMap<>();
            lastCommentValue.put("theJudeges", "e115c519-8395-4da2-b507-8a67ab3e0001");
            lastCommentValue.put("Comments", valueTables.get("OKRnextQuarter1").toString());
            commentValues.add(lastCommentValue);

            List<DataItemParam> params = new ArrayList<>();
            params.add(new DataItemParam("TeamClassify", teamType));
            params.add(new DataItemParam("TeamName", teamName));
            params.add(new DataItemParam("Year11", nowYear));
            params.add(new DataItemParam("Quarter", nextQuarter));
            params.add(new DataItemParam("OkrContent", parentOkrValues));
            params.add(new DataItemParam("TheJudgesReview", commentValues));

            //发起人
            User user = (User) getEngine().getOrganization().GetUnit(instanceData.getInstanceContext().getOriginator());

            //发起流程
            BPMServiceResult bpmServiceResult = bpmService.StartWorkflow("H3", "Authine", "TeamDepartmentOKR", user.getCode(), false, params);

            //等待1秒
            Thread.sleep(500);
            String workItemId = SqlUtil.doQuery(String.format("select  objectid from OT_workitem where instanceId = '%s' and ActivityCode = 'Activity2' and Participant = '%s' limit 1", bpmServiceResult.getInstanceId(), user.getObjectID())).getRows().get(0).getString(0);

            String pc_url = "http://www.kumhosunny.cn:8099/Portal/template/ddhome.html?loginfrom=dingtalk&WorkItemID=" + workItemId + "&time=" + System.currentTimeMillis();
            String mobile_url = "http://www.kumhosunny.cn:8099/Mobile/#/dingtalkmsg/" + workItemId + "?time=" + System.currentTimeMillis();

            //发送消息通知用户
            //子流程数据
            InstanceData sonData = new InstanceData(getEngine(), bpmServiceResult.getInstanceId(), User.AdministratorID);

            Notification notification = new Notification(OThinker.H3.Entity.Notification.NotifyType.DingTalk, null, user.getObjectID(),
                    user.getDingTalkAccount(), null, 0, bpmServiceResult.getInstanceId(),
                    "下季度OKR制定已发起" + sonData.getInstanceContext().getInstanceName(), "您有一条流程待办,点击查看", null, mobile_url, pc_url, null);

            getEngine().getNotifier().Notify(notification);

        } catch (Exception e) {
            e.printStackTrace();
        }


        return resultCode;
    }


}
